package com.jinke.api.modules.third.sjgj2.util;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jinke.api.common.annotation.Apilog;
import com.jinke.api.common.util.CommonUtil;
import com.jinke.api.modules.app.util.MathUtil;
import com.jinke.api.modules.third.ezeeship.model.request.EstimateRateRequest;
import com.jinke.api.modules.third.ezeeship.util.EzeeShipUtil;
import com.jinke.api.modules.third.sjgj.model.request.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
@RequiredArgsConstructor
public class Sjgjwl2Util {
    private static final String CREATEORDER_PHP = "https://sj.tanwapost.com/xapi/createorder.php";
    private static final String GETLABELS_PHP = "https://sj.tanwapost.com/xapi/getlabels.php";
    private static final String CANCEL_PHP = "https://sj.tanwapost.com/xapi/cancel.php";
    private static final String TRACKING_PHP = "https://sj.tanwapost.com/xapi/tracking.php";
    private static final String CHANNEL_PHP = "https://sj.tanwapost.com/xapi/channel.php";
    private static final String GETPRICE_PHP = "https://sj.tanwapost.com/xapi/getprice.php";
    private static String apiKey = "tw_5119";
    private static String apiSecret = "70873e8580c9900986939611618d7b1e";

    public static String sendPostRequest(String url, String requestBody) throws IOException {
        String seq = CommonUtil.getOrderNo();
        HttpURLConnection connection = null;
        try {
            // 创建连接
            URL apiUrl = new URL(url);
            connection = (HttpURLConnection) apiUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            // 写入请求体
            try (OutputStream outputStream = connection.getOutputStream()) {
                outputStream.write(requestBody.getBytes("UTF-8"));
            }

            // 获取响应
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                log.info("rec :  {}, {}", seq, response.toString());
                return response.toString();
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }


    @Apilog(requestTypeName = "gjsj2-估价")
    public static String getPrice(EstimateRateRequest estimateRateRequest, String qdId) {
        // 设置API端点URL
        CreateOrderRequest orderRequest = getCreateOrderRequest(estimateRateRequest, qdId);
        String requestBody = JSONUtil.toJsonStr(orderRequest);
        try {
            // 发送POST请求
            log.info("------------盛进国际2 估价请求参数------------>,{},{}", estimateRateRequest.getOrderNO(), requestBody);

            String response = sendPostRequest(GETPRICE_PHP, requestBody);

            log.info("------------盛进国际2 估价响应结果------------>,{},{}", estimateRateRequest.getOrderNO(), response);

            return response;
        } catch (IOException e) {
            log.info("------------盛进国际2 估价异常------------>,{}", estimateRateRequest.getOrderNO());

            e.printStackTrace();
        }
        return Strings.EMPTY;
    }

    public static String getLabels(GetLabelsRequest request) {

        String requestBody = JSONUtil.toJsonStr(request);

        try {
            // 发送POST请求
            String response = sendPostRequest(GETLABELS_PHP, requestBody);
            // 处理响应
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Strings.EMPTY;
    }

    @Apilog(requestTypeName = "sjgj2-取消")
    public static String cancelLabel(String objectId, String orderNo) {
        CancelRequest request = new CancelRequest();
        request.setOrderid(objectId);
        request.setApikey(apiKey);
        request.setApisecret(apiSecret);
        String param = JSONUtil.toJsonStr(request);

        try {
            log.info("------------盛进国际2 取消参数------------>,{},{}", orderNo, param);

            String response = sendPostRequest(CANCEL_PHP, param);
            log.info("------------盛进国际2 取消响应------------>,{},{}", orderNo, param);

            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Strings.EMPTY;
    }

    public static String tracking(String tracingNo) {
        TrackingRequest request = new TrackingRequest();
        request.setTrackingno(tracingNo);
        request.setApikey(apiKey);
        request.setApisecret(apiSecret);
        String requestBody = JSONUtil.toJsonStr(request);

        try {
            // 发送POST请求
            String response = sendPostRequest(TRACKING_PHP, requestBody);
            // 处理响应
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Strings.EMPTY;
    }

    @Apilog(requestTypeName = "gjsj2-下单")
    public static String createOrder(EstimateRateRequest estimateRateRequest, String qdId) {
        // 设置API端点URL
        CreateOrderRequest orderRequest = getCreateOrderRequest(estimateRateRequest, qdId);
        String requestBody = JSONUtil.toJsonStr(orderRequest);
        try {
            // 发送POST请求
            log.info("----------->盛进国际2----------->下单请求，{}，{}", estimateRateRequest.getOrderNO(), requestBody);
            String response = sendPostRequest(CREATEORDER_PHP, requestBody);
            // 处理响应
            log.info("----------->盛进国际2----------->下单响应，{}，{}", estimateRateRequest.getOrderNO(), response);
            return response;
        } catch (IOException e) {
            log.info("----------->盛进国际2----------->下单异常，{}", estimateRateRequest.getOrderNO());
            e.printStackTrace();
        }
        return Strings.EMPTY;
    }

    @NotNull
    private static CreateOrderRequest getCreateOrderRequest(EstimateRateRequest estimateRateRequest, String qdId) {
        // 将OrderRequest对象转换为JSON字符串
        // 创建OrderRequest对象
        CreateOrderRequest orderRequest = new CreateOrderRequest();

// 设置属性值
        orderRequest.setApikey(apiKey);
        orderRequest.setApisecret(apiSecret);
        orderRequest.setQd_id(Integer.parseInt(qdId));
        estimateRateRequest.getOrderNO();
// 创建Orders对象
        CreateOrderRequest.Orders orders = new CreateOrderRequest.Orders();
        orders.setCargo_type(2);
        orders.setOrderID(estimateRateRequest.getPlatformNo());
        EstimateRateRequest.Address from = estimateRateRequest.getFrom();
        orders.setFname(from.getPersonName());
        orders.setFtel(from.getPhone());
        orders.setFadd1(from.getAddressLine1() + ";" + from.getAddressLine2());
        orders.setFstate(from.getStateCode());
        orders.setFcity(from.getCity());
        orders.setFpostcode(from.getZipCode());
        orders.setFcountry(from.getCountryCode());

        EstimateRateRequest.Address to = estimateRateRequest.getTo();
        orders.setSname(to.getPersonName());
        orders.setScompany(to.getCompany());
        orders.setSadd1(to.getAddressLine1());
        orders.setSadd2(to.getAddressLine2());
        orders.setScity(to.getCity());
        orders.setSstate(to.getStateCode());
        orders.setSpostcode(to.getZipCode());
        orders.setStel(to.getPhone());
        orders.setScountry(to.getCountryCode());
        //   orders.setCkid(1);
        List<EstimateRateRequest.Parcel> requestParcels = estimateRateRequest.getParcels();
        orders.setParcel_num(requestParcels.size());


        EstimateRateRequest.LabelExtra extra = estimateRateRequest.getExtra();

        if (extra != null) {
            String reference = extra.getReference();
            if (StringUtils.isNotBlank(reference) && StringUtils.isNotEmpty(extra.getReference2())) {
                reference = reference + "; " + extra.getReference2();
            }
            orders.setNote(reference);

        }

        final BigDecimal[] totalWeight = {BigDecimal.ZERO};
        List<CreateOrderRequest.Parcels> parcelsList = requestParcels.stream().map(x -> {
            // 创建Parcels对象
            CreateOrderRequest.Parcels parcels = new CreateOrderRequest.Parcels();
            parcels.setBox(x.getPackageNum().toString());
            //  parcels.setBoxnote("label reference");
            BigDecimal weight = BigDecimal.valueOf(Double.parseDouble(x.getWeight()));

            if ("lb".equals(x.getMassUnit())) {
                weight = MathUtil.lb2kg(weight);
            }

            BigDecimal length = BigDecimal.valueOf(Double.parseDouble(x.getLength()));
            BigDecimal width = BigDecimal.valueOf(Double.parseDouble((x.getWidth())));
            BigDecimal height = BigDecimal.valueOf(Double.parseDouble(x.getHeight()));
            if ("in".equals(x.getDistanceUnit())) {
                length = MathUtil.in2cm(weight);
                width = MathUtil.in2cm(weight);
                height = MathUtil.in2cm(weight);
            }
            parcels.setLength(length);
            parcels.setWidth(width);
            parcels.setHeight(height);
            parcels.setWeight(weight);

            totalWeight[0] = totalWeight[0].add(weight);

            return parcels;
        }).collect(Collectors.toList());
        orders.setWeight(totalWeight[0]);

// 设置Parcels对象到Orders对象
        orders.setParcels(parcelsList);

// 设置Orders对象到OrderRequest对象
        orderRequest.setOrders(Arrays.asList(orders));
        return orderRequest;
    }

    public static String getChannel() {
        // 设置API端点URL

        // 将OrderRequest对象转换为JSON字符串
        // 创建OrderRequest对象
        BaseEntity orderRequest = new BaseEntity();

        // 设置属性值
        orderRequest.setApikey(apiKey);
        orderRequest.setApisecret(apiSecret);

        String requestBody = JSONUtil.toJsonStr(orderRequest);

        try {
            // 发送POST请求

            String response = sendPostRequest(CHANNEL_PHP, requestBody);

            // 处理响应
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


}
